<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试题名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入试题名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属科目" prop="subjectId">
        <treeselect v-model="queryParams.subjectId" :options="subjectOptions" :normalizer="normalizer" placeholder="请选择科目" style="width:240px"/>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['study:studyQuestion:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['study:studyQuestion:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studyQuestionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试题名称" align="center" prop="title" />
      <el-table-column label="所属科目" align="center" prop="subjectId" />
      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="附件" align="center" prop="fileId">
        <template slot-scope="scope">
          <span v-html="getDownLink(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="错误次数" align="center" prop="wrongCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['study:studyQuestion:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['study:studyQuestion:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
       <el-tabs type="card" >
        <el-tab-pane label="基本信息">
          <el-form-item label="试题名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入试题名称" />
          </el-form-item>
            <el-form-item label="所属科目" prop="subjectId">
              <treeselect v-model="form.subjectId" :options="subjectOptions" :normalizer="normalizer" placeholder="请选择科目"/>
            </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择类型">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="附件" prop="fileId">
              <span v-html="getDownLink(form)" v-if="form.file != null"></span>
              <el-upload
                ref="upload"
                :limit="1"
                accept=".doc, .docx, .pdf, .jpg, .jpeg, .png"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许上传文档或者图片文件！</div>
              </el-upload>
          </el-form-item>
          <el-form-item label="题目是否正确" v-if="form.type == '3'">
            <el-radio-group v-model="form.answer">
              <el-radio
                v-for="dict in booleanOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="正确答案" prop="answer" v-if="form.type == '4'">
            <el-input v-model="form.answer" placeholder="请输入正确答案" />
          </el-form-item>
          <el-form-item label="答案解析" prop="analyzes">
            <el-input v-model="form.analyzes" placeholder="请输入答案解析" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="错误次数" prop="wrongCount" v-if="form.id">
            <el-input v-model="form.wrongCount" disabled placeholder="请输入错误次数" />
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="选项信息">
            <el-table v-loading="loading" :data="form.optionList">
              <el-table-column label="选项" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.title" placeholder="请输入选项内容"/>
                </template>
              </el-table-column>
              <el-table-column label="是否为正确答案" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.isAnswer">
                    <el-radio
                      v-for="dict in booleanOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue"
                    >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
        </el-tab-pane>
      </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudyQuestion, getStudyQuestion, delStudyQuestion, addStudyQuestion, updateStudyQuestion, exportStudyQuestion } from "@/api/study/studyQuestion";
import { listStudySubject} from "@/api/study/studySubject";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "StudyQuestion",
  components: {
     Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedStudyOption: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题表格数据
      studyQuestionList: [],
      // 科目树选项
      subjectOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型字典
      typeOptions: [],
      // 状态字典
      statusOptions: [],
      // 状态字典
      booleanOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        subjectId: null,
        type: null,
        status: null,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sys/files/upload"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "试题名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        subjectId: [
          { required: true, message: "科目不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("question_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getTreeselect();
    this.getDicts("common_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.booleanOptions = response.data;
    });
  },
  methods: {
    /** 查询试题列表 */
    getList() {
      this.loading = true;
      listStudyQuestion(this.queryParams).then(response => {
        this.studyQuestionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换科目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.title,
        children: node.children
      };
    },
    /** 查询科目下拉树结构 */
    getTreeselect() {
      listStudySubject().then(response => {
        this.subjectOptions = [];
        const data = { id: 0, title: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "pid");
        this.subjectOptions.push(data);
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    /** 下载附件链接 */
    getDownLink(row) {
      if(row.file && row.file.id){
        return '<a href="'+process.env.VUE_APP_BASE_API+'/'+row.file.path+'" target="_blank">'+row.file.title+'</a>';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        subjectId: null,
        type: null,
        fileId: null,
        answer: null,
        analyzes: null,
        status: "1",
        wrongCount: null,
        // 试题选项表格数据
        optionList: []
      };
      for(var i=0;i<8;i++){
        this.form.optionList.push({title:'',isAnswer:'N'});
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试题";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStudyQuestion(id).then(response => {
        this.form = response.data;
        for(var i=0;i<2;i++){
          this.form.optionList.push({title:'',isAnswer:'N'});
        }
        this.open = true;
        this.title = "修改试题";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.studyOptionList = this.studyOptionList;
          if (this.form.id != null) {
            updateStudyQuestion(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudyQuestion(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.form.fileId = response.data.id
      this.form.file = response.data
      this.$refs.upload.clearFiles();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除试题编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStudyQuestion(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
	/** 试题选项序号 */
    rowStudyOptionIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 试题选项添加按钮操作 */
    handleAddStudyOption() {
      let obj = {};
      obj.title = "";
      this.studyOptionList.push(obj);
    },
    /** 试题选项删除按钮操作 */
    handleDeleteStudyOption() {
      if (this.checkedStudyOption.length == 0) {
        this.$alert("请先选择要删除的试题选项数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.studyOptionList.splice(this.checkedStudyOption[0].index - 1, 1);
      }
    },
    /** 单选框选中数据 */
    handleStudyOptionSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.studyOption.clearSelection();
        this.$refs.studyOption.toggleRowSelection(selection.pop());
      } else {
        this.checkedStudyOption = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有试题数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStudyQuestion(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
